package com.zhangfei.tutorial;

import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

@RestController
@RequestMapping("/api/tutorials")
@CrossOrigin
public class TutorialController {
    private final TutorialRepository tutorialRepository;

    public TutorialController(TutorialRepository tutorialRepository) {
        this.tutorialRepository = tutorialRepository;
    }

    @GetMapping
    public List<Tutorial> getTutorials(@RequestParam(value = "searchName", required = false) String searchName) {
        if (StringUtils.hasText(searchName)) {
            return this.tutorialRepository.findByTitleContains(searchName);
        }

        return this.tutorialRepository.findAll();
    }

    @GetMapping("/{id}")
    public Tutorial getTutorial(@PathVariable Long id) {
        return this.tutorialRepository.findById(id).get();
    }

    @PostMapping
    public ResponseEntity createTutorial(@RequestBody Tutorial tutorial) throws URISyntaxException {
        Tutorial model = this.tutorialRepository.save(tutorial);
        return ResponseEntity.created(new URI("/teachers/" + model.getId())).body(model);
    }

    @PutMapping("/{id}")
    public ResponseEntity updateTutorial(@PathVariable Long id, @RequestBody Tutorial tutorial) {
        Tutorial model = this.tutorialRepository.findById(id).get();
        model.setTitle(tutorial.getTitle());
        model.setDescription(tutorial.getDescription());

        this.tutorialRepository.save(model);
        return ResponseEntity.ok(model);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deleteTutorial(@PathVariable Long id) {
        Tutorial tutorial = this.tutorialRepository.findById(id).get();
        this.tutorialRepository.delete(tutorial);
        return ResponseEntity.ok(tutorial);
    }
}
